import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render

from django.core.paginator import Paginator

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import GoodsCategory,SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb
from apps.orders.models import OrderInfo, OrderGoods
from utils.response_code import RETCODE
from apps.contents.utils import get_categories
from django.utils import timezone


class ListView(View):
    def get(self, request, category_id,page_num):

        try:
            category = GoodsCategory.objects.get(pk=category_id)
        except GoodsCategory.DoesNotExist:
            return render(request, '404.html')
        breadcrumb = get_breadcrumb(category)


        sort = request.GET.get('sort')

        if sort == 'defult':
            sort_filed = 'create_time'
        elif sort == 'price':
            sort_filed = '-price'
        else:
            sort_filed = 'sales'
            sort = 'hot'

        skus = SKU.objects.filter(category=category).order_by(sort_filed)
        try:
            paginator = Paginator(skus,5)
            pages_sku = paginator.page(page_num)
            total_pages = paginator.num_pages
        except Exception as e :
            return render(request,'404.html')




        context = {
            'breadcrumb': breadcrumb,
            'sort':sort,
            'category':category,
            'page_skus':pages_sku,
            'total_page':total_pages,
            'page_num':page_num,
        }
        return render(request, 'list.html', context=context)



class HotView(View):
    def get(self,request,category_id):
        try:
            category = GoodsCategory.objects.get(pk = category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'未找到该类型'})

        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]
        skus_list = []
        for sku in skus:
            skus_list.append({
                'id' : sku.id,
                'name': sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url

            })
        return http.JsonResponse({'code':RETCODE.OK,'mrrmsg':'ok','hot_skus':skus_list})



class DetailView(View):
    def get(self,request,sku_id):
        try:
            sku = SKU.objects.get(id = sku_id)

        except Exception as e :
            return render(request,'404.html')

        categories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)
        sku_specs = sku.specs.order_by('spec_id')
        sku_key=[]
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        skus = sku.spu.sku_set.all()
        spec_sku_map = {}
        for s in skus:
            s_specs = s.specs.order_by('spec_id')
            key = []
            for spec in s_specs:
                key.append(spec.option.id)

            spec_sku_map[tuple(key)] = s.id
            goods_specs = sku.spu.specs.order_by('id')
            if len(sku_key) < len(goods_specs):
                return
            for index, spec in enumerate(goods_specs):
                key = sku_key[:]
                spec_options = spec.options.all()
                for option in spec_options:
                    key[index] = option.id
                    option.sku_id = spec_sku_map.get(tuple(key))
                spec.spec_options = spec_options



        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)



class VisitView(View):
    def post(self,request):
        data = json.loads(request.body.decode())
        categroy_id = data.get('category_id')
        try:
            category = GoodsCategory.objects.get(pk = categroy_id)
        except Exception as e :
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'分类不存在'})
        today = timezone.localdate()
        try:
            gvc =GoodsVisitCount.objects.get(
                category = category,
                date = today,
            )
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(
                category=category,
                date = today,
                count = 1,
            )
        else:
            gvc.count+=1
            gvc.save()
        return http.JsonResponse({'code':RETCODE.OK})


class OrderCommentView(LoginRequiredMixin,View):
    def get(self,request):
        order_id = request.GET.get('order_id')
        try:
            OrderInfo.objects.filter(order_id=order_id,user = request.user)
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('订单不存在')
        try:
            skus = OrderGoods.objects.filter(order_id=order_id, is_commented=False)
        except Exception as e:
            return http.HttpResponseBadRequest('订单错误')
        uncomments_list = []
        for sku in skus:
            uncomments_list.append({
                'order_id':sku.order.order_id,
                'sku_id':sku.sku.id,
                'name':sku.sku.name,
                'price':str(sku.price),
                'default_image_url':sku.sku.default_image.url,
                'comment':sku.comment,
                'display_score':sku.score,
                'is_anonymous':str(sku.is_anonymous),
            })
        context = {
            'skus' : uncomments_list
        }
        return render(request,'goods_judge.html',context=context)
    def post(self,request):
        data = json.loads(request.body.decode())
        order_id = data.get('order_id')
        sku_id = data.get('sku_id')
        score = data.get('score')
        comment = data.get('comment')
        is_anonymous = data.get('is_anonymous')
        if not all([order_id, sku_id, score, comment]):
            return http.HttpResponseBadRequest('参数不全')
        try:
            OrderInfo.objects.filter(order_id=order_id,user = request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('order_id有误')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id错误')
        if is_anonymous:
            if not isinstance(is_anonymous, bool):
                return http.HttpResponseForbidden('is_anonymous错误')
        OrderGoods.objects.filter(order_id=order_id,sku_id=sku_id,is_commented=False).update(
            comment=comment,
            score=score,
            is_anonymous=is_anonymous,
            is_commented = True,
        )
        sku.comments += 1
        sku.save()
        sku.spu.comments += 1
        sku.spu.save()
        if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0:
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

class GoodsCommentView(View):
    def get(self, request, sku_id):
        order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:30]

        goods_comment_list = []
        for order_goods in order_goods_list:
            username = order_goods.order.user.username
            goods_comment_list.append({
                'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username,
                'comment': order_goods.comment,
                'score': order_goods.score,
            })
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'goods_comment_list': goods_comment_list})

















